// 通知管理
const NotificationManager = {
  async showNotification(title, message) {
    try {
      // 添加调试日志
      console.log('Showing notification:', { title, message });
      
      // 请求通知权限
      if (Notification.permission !== 'granted') {
        const permission = await Notification.requestPermission();
        if (permission !== 'granted') {
          console.log('Notification permission denied');
          return;
        }
      }

      // 创建通知
      const notification = await chrome.notifications.create({
        type: 'basic',
        iconUrl: chrome.runtime.getURL('icons/icon48.png'),
        title: title,
        message: message,
        priority: 2,
        requireInteraction: true
      });
      
      console.log('Notification created:', notification);
    } catch (error) {
      console.error('Error showing notification:', error);
    }
  }
};

// 存储管理
const StorageManager = {
  async getReminders() {
    const data = await chrome.storage.local.get('reminders');
    return data.reminders || [];
  },

  async saveReminder(reminder) {
    const reminders = await this.getReminders();
    reminders.push(reminder);
    await chrome.storage.local.set({ reminders });
  },

  async markAsCompleted(reminderId) {
    const reminders = await this.getReminders();
    const updatedReminders = reminders.map(r => {
      if (r.id === reminderId) {
        return { ...r, completed: true, completedAt: new Date() };
      }
      return r;
    });
    await chrome.storage.local.set({ reminders: updatedReminders });
  },

  async updateReminder(reminder) {
    const reminders = await this.getReminders();
    const updatedReminders = reminders.map(r => 
      r.id === reminder.id ? reminder : r
    );
    await chrome.storage.local.set({ reminders: updatedReminders });
  },

  async cleanupOldReminders(days) {
    const reminders = await this.getReminders();
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);
    
    const filteredReminders = reminders.filter(reminder => {
      if (!reminder.completed) return true;
      const reminderDate = new Date(reminder.completedAt);
      return reminderDate > cutoffDate;
    });
    
    await chrome.storage.local.set({ reminders: filteredReminders });
  }
};

// 定时检查提醒任务
chrome.alarms.create('checkReminders', { periodInMinutes: 1 });

// 监听定时器
chrome.alarms.onAlarm.addListener(async (alarm) => {
  try {
    console.log('Alarm triggered:', alarm.name);
    
    if (alarm.name === 'checkReminders') {
      const reminders = await StorageManager.getReminders();
      const now = new Date();
      
      console.log('Checking reminders:', reminders);
      
      for (const reminder of reminders) {
        if (reminder.completed) continue;
        
        if (reminder.type === 'fixed') {
          // 处理定点提醒
          const reminderTime = new Date(reminder.time);
          const diffMinutes = Math.abs(now - reminderTime) / (1000 * 60);
          
          console.log('Fixed reminder check:', {
            reminder,
            now: now.toISOString(),
            reminderTime: reminderTime.toISOString(),
            diffMinutes
          });
          
          if (diffMinutes <= 1) {
            console.log('Triggering fixed reminder:', reminder);
            await NotificationManager.showNotification('定点提醒', reminder.text);
            await StorageManager.markAsCompleted(reminder.id);
          }
        } else if (reminder.type === 'interval') {
          // 处理间隔提醒
          const currentHour = now.getHours();
          const currentMinutes = now.getMinutes();
          const currentTime = `${currentHour.toString().padStart(2, '0')}:${currentMinutes.toString().padStart(2, '0')}`;
          
          console.log('Interval reminder check:', {
            reminder,
            currentTime,
            quietTime: reminder.quietStart && reminder.quietEnd ? 
              `${reminder.quietStart}-${reminder.quietEnd}` : 'None'
          });
          
          // 检查是否在免打扰时间
          if (reminder.quietStart && reminder.quietEnd) {
            if (currentTime >= reminder.quietStart && currentTime <= reminder.quietEnd) {
              console.log('Reminder in quiet hours, skipping');
              continue;
            }
          }
          
          // 检查今日提醒次数
          if (reminder.maxDaily && reminder.todayCount >= reminder.maxDaily) {
            console.log('Daily limit reached, skipping');
            continue;
          }
          
          const lastNotification = new Date(reminder.lastNotification || 0);
          const diffMinutes = Math.floor((now - lastNotification) / (1000 * 60));
          
          console.log('Time since last notification:', diffMinutes, 'minutes');
          
          if (diffMinutes >= reminder.interval) {
            console.log('Triggering interval reminder:', reminder);
            await NotificationManager.showNotification('间隔提醒', reminder.text);
            reminder.lastNotification = now;
            reminder.todayCount = (reminder.todayCount || 0) + 1;
            await StorageManager.updateReminder(reminder);
          }
        }
      }
    }
  } catch (error) {
    console.error('Error in alarm handler:', error);
  }
});

// 每天凌晨重置计数
chrome.alarms.create('resetDaily', { 
  when: getNextMidnight(),
  periodInMinutes: 24 * 60 
});

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === 'resetDaily') {
    const reminders = await StorageManager.getReminders();
    for (const reminder of reminders) {
      if (reminder.type === 'interval') {
        reminder.todayCount = 0;
        await StorageManager.updateReminder(reminder);
      }
    }
  }
});

// 定期清理已完成的提醒
chrome.alarms.create('cleanup', { periodInMinutes: 24 * 60 });
chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === 'cleanup') {
    await StorageManager.cleanupOldReminders(7); // 默认7天
  }
});

function getNextMidnight() {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0);
  return tomorrow.getTime();
} 